<!-- 翻页表格组件 -->
<template>
  <a-table ref="TableRef" :data="tableList" :pagination="isTurn ? false : pagination" @page-change="
      pageChangeDiy ? pageChangeDiy($event, 'page') : pageChange($event, 'page')
    " @page-size-change="
      pageChangeDiy ? pageChangeDiy($event, 'size') : pageChange($event, 'size')
    " :scroll="{
      x: width,
      y: height ? height : globalParameters.windowHeight - winHeightReduce,
    }" v-bind="args ? { ...args } : null" :row-key="rowKey" @select="onSelect" @select-all="onSelectAll" :loading="loading" :stripe="true" v-model:selected-keys="selectedKeys">
    <!-- arco-table的插槽，默认为columns -->
    <template #columns>
      <slot />
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue';
import { useGlobalParametersStore } from '@/store';
import { cloneDeep } from 'lodash';
import miiter from '@/utils/mitt';

export interface paramsType {
  page: number;
  size: number;
}

let loading = ref(false);
const selectedKeys = ref<number[]>([]);

const globalParameters = useGlobalParametersStore();

const props = withDefaults(
  // 参数说明
  defineProps<{
    tableData: (params: any) => any; // 请求table数据的函数
    width?: string | number; // 表格的实际宽度，用来显示滚轮,  有默认值
    height?: string | number; // 表格的实际高度，用来显示滚轮,  不传默认使用winHeightReduce
    args?: any; // 对象，放置a-table的剩余属性
    winHeightReduce?: number; // 表格的实际高度,height不传时使用这个, 计算为窗口高度减去值，有默认值
    isShowPagination?: boolean; // 是否显示分页
    rowKey?: string;
    pageChangeDiy?: (x: number, y: 'page' | 'size') => void; // 自定义分页
  }>(),
  {
    width: '100%',
    winHeightReduce: 300,
    isShowPagination: true,
    args: {
      bordered: {
        headerCell: true,
      },
      stripe: true,
    },
    rowKey: 'id',
  }
);

const TableRef = ref();

const pagination = reactive({
  // 分页数据
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  current: 1,
  total: 0,
});
const params = reactive({
  // 分页数据，用于请求
  page: 1,
  size: 10,
});
const isDisabled = ref(true);
const tableList = ref<any>([]); // 储存表格数据
const selectedList = ref<any>([]); // 储存选中的数据
const selectedIndex = ref<any>([]);
let isTurn = ref(false);
const loadData = async () => {
  // 加载表格数据
  loading.value = true;
  try {
    const res = await props.tableData(params);
    const { content, pageable } = res;
    if (pageable) {
      tableList.value = content || [];
      pagination.current = pageable.pageNumber;
      pagination.total = pageable.totalItems;
    } else if (Array.isArray(res)) {
      tableList.value = res;
      isTurn.value = true;
    }
    loading.value = false;
  } catch (err) {
    loading.value = false;
  }
  loading.value = false;
};

const pageChange = (val: number, key: 'page' | 'size') => {
  if (isTurn.value || props.pageChangeDiy) return;
  params[key] = val;
  loadData();
};
loadData();

// 选择数据事件
const onSelect = (rowKeys: any, rowKey: any, record: any) => {
  if (TableRef.value.rowSelection.type === 'radio') {
    selectedList.value[0] = record;
  } else {
    const index = selectedList.value.findIndex((item: any) => {
      return item.id === rowKey;
    });
    if (index === -1) {
      selectedList.value.push(record);
      isDisabled.value = false;
      miiter.emit('selectedDis', isDisabled.value);
    } else {
      selectedList.value.splice(index, 1);
      if (selectedList.value.length === 0) {
        isDisabled.value = true;
        miiter.emit('selectedDis', isDisabled.value);
      }
    }
  }
  // const index = selectedList.value.findIndex((item: any) => {
  //   return item.id === rowKey;
  // });
  // if (index === -1) {
  //   selectedList.value.push(record);
  //   isDisabled.value = false;
  //   miiter.emit('selectedDis', isDisabled.value);
  // } else {
  //   selectedList.value.splice(index, 1);
  //   if (selectedList.value.length === 0) {
  //     isDisabled.value = true;
  //     miiter.emit('selectedDis', isDisabled.value);
  //   }
  // }
};

// 全选按钮
const onSelectAll = (checked: boolean) => {
  if (checked) {
    selectedList.value = cloneDeep(tableList.value);
    isDisabled.value = false;
    miiter.emit('selectedDis', isDisabled.value);
  } else {
    selectedList.value = [];
    isDisabled.value = true;
    miiter.emit('selectedDis', isDisabled.value);
  }
};

const refreshPaging = () => {
  params.page = 1;
  params.size = 10;
};

/*
    对外暴露loadData和tableList
    loadData: 用来更新表格数据，可以在模糊搜索时使用
    tableList: 用来新增删除表格行数的操作，可以用来新增一行的时候使用
    selectedList: 用来暴露选中的数据数组
  */
defineExpose({
  loadData,
  tableList,
  selectedList,
  selectedKeys,
  isDisabled,
  refreshPaging,
});
</script>

<style scoped lang="less">
  :deep(.arco-table-th),
  :deep(.arco-table-td) {
    // height: 30px;
  }

  :deep(.arco-table-th) {
    font-weight: 700;
  }

  :deep(.arco-table-cell) {
    justify-content: center;
    text-align: center;
  }
</style>
